package com.wuseguang.springcloud.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wuseguang.springcloud.Classcardservice.ClassCardFieldService;
import com.wuseguang.springcloud.Classcardservice.ClassCardService;
import com.wuseguang.springcloud.JdbcTemplate.HaiweidaCooperativeSchoolJdbc;
import com.wuseguang.springcloud.JdbcTemplate.WXJdbc;
import com.wuseguang.springcloud.dao.jdbc.AttendanceJdbc;
import com.wuseguang.springcloud.util.CodeUtil;
import com.wuseguang.springcloud.util.DateUtil;
import com.wuseguang.springcloud.util.Result;
import com.wuseguang.springcloud.util.WeChat.TemplateTools;
import com.wuseguang.springcloud.util.WeChat.WXUtil;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.util.*;

@Service
public class AttendanceServiceImpl implements com.wuseguang.springcloud.service.AttendanceService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private AttendanceJdbc attendanceJdbc;

    @Autowired
    private ClassCardService classCardService;

    @Autowired
    private ClassCardFieldService service;
    @Autowired
    private WXJdbc wXJdbc;
    @Autowired
    private HaiweidaCooperativeSchoolJdbc haiweidaCooperativeSchoolJdbc;


    private static Integer flag = 0;

    private static Integer zhengchang = 1;//正常打卡

    private static Integer chidao = 2;//迟到

    private static Integer zaotui = 3;//早退

    private static Integer weidaka = 4;//未打卡

    private static Integer qingjia = 5;//请假

    /**
     * @描述 班牌人脸考勤 添加考勤
     * @创建人 zm
     * @创建时间 2020/2/22
     */
    @Transactional
    @Override
    public Result addAttend(String deviceid, Integer userid, Integer groupid, Integer grouptype, Integer shiftid, String time) {
        Map<String, Object> stringObjectMap = attendanceJdbc.queryDevice(deviceid);
        if (stringObjectMap == null) {
            return new Result(CodeUtil.DEVICE_AFTER_OPERATION);
        }
        Map<String, Object> map1 = null;
        try {
            String sql = "";
            if (grouptype == 0) {
                sql = "SELECT s.id,s.class_id classid FROM attendance_group_user u ,student s WHERE u.userid=s.id AND attend_group_id=? AND s.id=? LIMIT 1";
            } else {
                sql = "SELECT s.id FROM attendance_group_user u ,teacher s WHERE u.userid=s.id AND attend_group_id=? AND s.id=? LIMIT 1";
            }
            map1 = attendanceJdbc.queryMap(sql, groupid, userid);
        } catch (Exception e) {

        }
        if (map1 == null) {
            return new Result(CodeUtil.NOTAN_ATTENDANCEPERSON);
        }
        Object school_id = stringObjectMap.get("school_id");
        //查询班次详情
        String sql = "SELECT  type,starttime,endtime,starttime1,endtime1,s_ejecttime,e_ejecttime,s_ejecttime1,e_ejecttime1,school_id FROM attendance_shift WHERE id=? and state=0";
        Map<String, Object> map = null;
        try {
            map = attendanceJdbc.queryMap(sql, shiftid);
        } catch (Exception e) {
            logger.info("addAttend-->mapList,error={}", e);
        }
        if (map != null) {
            String gettime = DateUtil.gettime();
            String param = "";//开始时间
            String param1 = "";//结束时间
            int type = (int) map.get("type");//考勤类型:0 1天1次、1 1天2次
            String starttime = map.get("starttime") == null ? "" : (String) map.get("starttime");//第一段进班时间
            String endtime = map.get("endtime") == null ? "" : (String) map.get("endtime");//第一段离班时间
            String starttime1 = map.get("starttime1") == null ? "" : (String) map.get("starttime1");//第二段进班时间
            String endtime1 = map.get("endtime1") == null ? "" : (String) map.get("endtime1");//第二段离班时间
            starttime = DateUtil.AddTime(gettime, starttime);
            endtime = DateUtil.AddTime(gettime, endtime);
            starttime1 = DateUtil.AddTime(gettime, starttime1);
            endtime1 = DateUtil.AddTime(gettime, endtime1);
            int attendtype = 2;
            if (type == 0) {//一天一段考勤
                String s = "";
                if (!StringUtils.isEmpty(endtime) && !StringUtils.isEmpty(starttime1)) {//设置了中间休息时段  取中间时间 区分进班迟到 和 离班早退
                    long l = DateUtil.getcompTime(starttime1, endtime);
                    s = DateUtil.addtimeMinutes(endtime, (int) l / 2);
                } else {//未设置了中间休息时段  取中间时间 区分进班迟到 和 离班早退
                    long l = DateUtil.getcompTime(endtime1, starttime);
                    s = DateUtil.addtimeMinutes(starttime, (int) l / 2);
                }
                if (time.equals(starttime)) {//为第一段进班考勤
                    param = gettime;
                    param1 = s;
                    if (DateUtil.getcompTime(DateUtil.getTimeAndMinutes(), starttime) > 0) {
                        attendtype = 3;
                    }
                }
                if (time.equals(endtime1)) {//为第一段离班考勤
                    attendtype = 9;
                    param = s;
                    param1 = DateUtil.addDays(gettime, 1);
                    if (DateUtil.getcompTime(DateUtil.getTimeAndMinutes(), endtime1) < 0) {
                        attendtype = 6;
                    }
                }
            } else {//一天两段考勤
                logger.info("一天两段,starttime={},endtime={},starttime1={},endtime1={}", starttime, endtime, starttime1, endtime1);
                //求第一段考勤的中间时间  用来区分 进班迟到和离班早退
                long l = DateUtil.getcompTime(endtime, starttime);
                String s = DateUtil.addtimeMinutes(starttime, (int) l / 2);
                //求第一段考勤的结束时间和第二段开始时间的中间时间  用来区分 第一段离班正常和第二段的进班正常
                long l1 = DateUtil.getcompTime(starttime1, endtime);
                String s1 = DateUtil.addtimeMinutes(endtime, (int) l1 / 2);
                //求第二段考勤的中间时间  用来区分 第二段进班迟到和离班早退
                long l2 = DateUtil.getcompTime(endtime1, starttime1);
                String s3 = DateUtil.addtimeMinutes(starttime1, (int) l2 / 2);
                logger.info("一天两段，s={}，s1={}，s3={}", s, s1, s3);
                if (time.equals(starttime)) {//为第一段进班考勤
                    param = gettime;
                    param1 = s;
                    if (DateUtil.getcompTime(DateUtil.getTimeAndMinutes(), starttime) > 0) {
                        attendtype = 3;
                    }
                }
                if (time.equals(endtime)) {//为第一段离班考勤
                    attendtype = 9;
                    param = s;
                    param1 = s1;
                    if (DateUtil.getcompTime(DateUtil.getTimeAndMinutes(), endtime) < 0) {
                        attendtype = 6;
                    }
                }

                if (time.equals(starttime1)) {//为第二段进班考勤
                    param = s1;
                    param1 = s3;
                    if (DateUtil.getcompTime(DateUtil.getTimeAndMinutes(), starttime1) > 0) {
                        attendtype = 3;
                    }
                }

                if (time.equals(endtime1)) {//为第二段离班考勤
                    attendtype = 9;
                    param = s3;
                    param1 = DateUtil.addDays(gettime, 1);
                    if (DateUtil.getcompTime(DateUtil.getTimeAndMinutes(), endtime1) < 0) {
                        attendtype = 6;
                    }
                }
            }
            String sql1 = " SELECT COUNT(*) count FROM attend WHERE attend_group_id=? AND shift_id=? AND school_id=? " +
                    " AND userid=? AND state=0 AND attendtime>=? AND attendtime<=?";
            logger.info("groupid={}, shiftid={}, school_id={}, userid={}, param={}, param1={}", groupid, shiftid, school_id, userid, param, param1);
            Integer integer = attendanceJdbc.queryCount(sql1, groupid, shiftid, school_id, userid, param, param1);
            String sql2 = "insert into `attend` (`userid`, `attend_group_id`, `shift_id`,  `school_id`, `attendtime`, `opertime`, `state`)" +
                    " values(?,?,?,?,now(),now(),?)";
            if (integer == 0) {
                int i = attendanceJdbc.updateByParameter(sql2, userid, groupid, shiftid, school_id, 0);
                if (i > 0) {
                    if (grouptype == 0) {
                        addAttendanceNotice(userid, groupid, attendtype, map1);
                    }
                    HashMap<String, Integer> stringIntegerHashMap = new HashMap<>();
                    stringIntegerHashMap.put("attendtype", attendtype);
                    //推送考勤信息
                    //小程序推送
                    //attendPush(userid, attendtype);
                    //公众号推送
                    officialAccountPush(userid, attendtype);
                    return new Result(stringIntegerHashMap);
                }
                return new Result(CodeUtil.ATTENDANCE_FAILURE);
            }
            attendanceJdbc.updateByParameter(sql2, userid, groupid, shiftid, school_id, 1);
            return new Result(CodeUtil.REPEAT_ATTENDANCE);
        }
        return new Result(CodeUtil.ATTENDANCE_FAILURE);
    }

    /**
     * @描述 添加 考勤通知
     * 对考勤做出判断  考勤类型: 0 病假 1事假 2 正常 3 进班迟到 4进班缺卡 5 离班缺卡 6 离班早退 7 缺勤 8 未打卡 9离班正常
     * @创建人 zm
     * @创建时间 2020/3/1
     */
    public void addAttendanceNotice(Integer userid, Integer groupid, int attendtype, Map<String, Object> map) {
        String sql = "insert into `attendance_notice`(`student_id`,`class_id`,`attend_group_id`,`attendtype`,`opertime`) " +
                "values(?,?,?,?,now())";
        attendanceJdbc.updateByParameter(sql, userid, map.get("classid"), groupid, attendtype);
    }

    /**
     * @描述 查询该考勤组该段人员所有考勤状态
     * @创建人 zm
     * @创建时间 2020/2/20
     */
    @Override
    public Result queryAttendUserStatusAll(String deviceid, Integer groupid, Integer grouptype, Integer shiftid, String time) {
        try {
            Map<String, Object> stringObjectMap = attendanceJdbc.queryDevice(deviceid);
            if (stringObjectMap == null) {
                return new Result(CodeUtil.DEVICE_AFTER_OPERATION);
            }
            Map<String, Object> maps = new HashMap<>();
            String gettime = DateUtil.gettime();
            String time1 = DateUtil.time();
            Map<String, Object> map = null;
            if (!StringUtils.isEmpty(groupid) && groupid != 0) {
                String sql1 = "SELECT name string FROM attendance_group WHERE id=? ";
                String groupname = attendanceJdbc.queryString(sql1, groupid);//考勤组名称
                maps.put("name", groupname);
                maps.put("groupid", groupid);
                maps.put("shiftid", shiftid);
                maps.put("grouptype", grouptype);
                //查询班次详情
                String sql = "SELECT  type,starttime,endtime,starttime1,endtime1,s_ejecttime,e_ejecttime,s_ejecttime1,e_ejecttime1,school_id FROM attendance_shift WHERE id=? and state=0";
                try {
                    map = attendanceJdbc.queryMap(sql, shiftid);
                } catch (Exception e) {
                    logger.info("queryAttendUserStatusAll-->mapList,error={}", e);
                }
            } else {
                String sql1 = " SELECT g.id , g.name ,g.attend_group_type grouptype,f.id shiftid,f.type,f.starttime,f.endtime,f.starttime1,f.endtime1" +
                        " ,f.s_ejecttime,f.e_ejecttime,f.s_ejecttime1,f.e_ejecttime1,f.school_id FROM  " +
                        " attendance_group g,attendance_group_classid s,attendance_shift f WHERE s.class_id=? AND " +
                        " g.id=s.attend_group_id AND f.id=SUBSTRING_INDEX(SUBSTRING_INDEX(g.shift_id,',', ?), ',', -1)  ORDER BY f.starttime ";
                List<Map<String, Object>> mapList = null;
                try {
                    mapList = attendanceJdbc.queryListMap(sql1, stringObjectMap.get("classid"), DateUtil.getWeekInt(gettime));
                } catch (Exception e) {
                    logger.info("queryAttendUserStatusAll-->erorr={}", e);
                }
                if (mapList == null) {
                    return new Result();
                }
                for (int i = 0; i < mapList.size(); i++) {
                    if (mapList.size() == 1 || i == mapList.size() - 1) {
                        map = mapList.get(i);
                        maps.put("name", map.get("name"));
                        maps.put("groupid", map.get("id"));
                        maps.put("shiftid", map.get("shiftid"));
                        maps.put("grouptype", map.get("grouptype"));
                        break;
                    }
                    if (i <= mapList.size() - 2) {
                        Map<String, Object> map1 = mapList.get(i);
                        Map<String, Object> map2 = mapList.get(i + 1);
                        String endtime1 = map1.get("endtime1") == null ? "" : (String) map1.get("endtime1");
                        String starttime = map2.get("starttime") == null ? "" : (String) map2.get("starttime");
                        endtime1 = DateUtil.AddTime(gettime, endtime1);
                        starttime = DateUtil.AddTime(gettime, starttime);
                        long l = DateUtil.getcompTime(starttime, endtime1);
                        if (l > 0) {
                            String s = DateUtil.addtimeMinutes(endtime1, (int) l / 2);
                            if (DateUtil.getcompTime(time1, s) <= 0) {
                                map = mapList.get(i);
                                maps.put("name", map.get("name"));
                                maps.put("groupid", map.get("id"));
                                maps.put("shiftid", map.get("shiftid"));
                                maps.put("grouptype", map.get("grouptype"));
                                break;
                            }
                        } else {
                            logger.info("班牌设置的考勤时间有冲突。。。");
                        }
                    }
                }
            }
            if (map != null) {
                if (StringUtils.isEmpty(groupid) || groupid == 0) {
                    groupid = (int) map.get("id");
                    grouptype = (int) map.get("grouptype");
                    shiftid = (int) map.get("shiftid");
                }
                int a = 0;
                int type = (int) map.get("type");//考勤类型:0 1天1次、1 1天2次
                String s_ejecttime = map.get("s_ejecttime") == null ? "" : (String) map.get("s_ejecttime");//第一段进班弹出dialog 时间
                String e_ejecttime = map.get("e_ejecttime") == null ? "" : (String) map.get("e_ejecttime");//第一段离班弹出dialog 时间
                String s_ejecttime1 = map.get("s_ejecttime1") == null ? "" : (String) map.get("s_ejecttime1");//第二段进班弹出dialog 时间
                String e_ejecttime1 = map.get("e_ejecttime1") == null ? "" : (String) map.get("e_ejecttime1");//第二段离班弹出dialog 时间
                String starttime = map.get("starttime") == null ? "" : (String) map.get("starttime");//第一段进班时间
                String endtime = map.get("endtime") == null ? "" : (String) map.get("endtime");//第一段离班时间
                String starttime1 = map.get("starttime1") == null ? "" : (String) map.get("starttime1");//第二段进班时间
                String endtime1 = map.get("endtime1") == null ? "" : (String) map.get("endtime1");//第二段离班时间
                starttime = DateUtil.AddTime(gettime, starttime);
                endtime = DateUtil.AddTime(gettime, endtime);
                starttime1 = DateUtil.AddTime(gettime, starttime1);
                endtime1 = DateUtil.AddTime(gettime, endtime1);
                String s = "";
                String s1 = "";
                String s2 = "";
                String s3 = "";
                if (type == 0) {
                    if (!StringUtils.isEmpty(endtime) && !StringUtils.isEmpty(starttime1)) {//设置了中间休息时段  取中间时间 区分进班迟到 和 离班早退
                        long l = DateUtil.getcompTime(starttime1, endtime);
                        s = DateUtil.addtimeMinutes(endtime, (int) l / 2);
                    } else {//未设置了中间休息时段  取中间时间 区分进班迟到 和 离班早退
                        long l = DateUtil.getcompTime(endtime1, starttime);
                        s = DateUtil.addtimeMinutes(starttime, (int) l / 2);
                    }
                } else {
                    logger.info("一天两段,starttime={},endtime={},starttime1={},endtime1={}", starttime, endtime, starttime1, endtime1);
                    //求第一段考勤的中间时间  用来区分 进班迟到和离班早退
                    long l = DateUtil.getcompTime(endtime, starttime);
                    s2 = DateUtil.addtimeMinutes(starttime, (int) l / 2);
                    //求第一段考勤的结束时间和第二段开始时间的中间时间  用来区分 第一段离班正常和第二段的进班正常
                    long l1 = DateUtil.getcompTime(starttime1, endtime);
                    s1 = DateUtil.addtimeMinutes(endtime, (int) l1 / 2);
                    //求第二段考勤的中间时间  用来区分 第二段进班迟到和离班早退
                    long l2 = DateUtil.getcompTime(endtime1, starttime1);
                    s3 = DateUtil.addtimeMinutes(starttime1, (int) l2 / 2);
                }
                logger.info("time={}", time);
                if ((!StringUtils.isEmpty(time) && time.equals(s_ejecttime)) || (type == 0 && DateUtil.getcompTime(time1, s) <= 0) || (type == 1 && DateUtil.getcompTime(time1, s2) <= 0)) {//为第一段进班考勤
                    maps.put("attendtime", new StringBuilder("进班考勤: ").append(starttime).toString());
                    maps.put("time", starttime);
                    a = 1;
                }
                if ((!StringUtils.isEmpty(time) && time.equals(e_ejecttime)) || (type == 1 && DateUtil.getcompTime(time1, s2) > 0 && DateUtil.getcompTime(time1, s1) <= 0)) {//为第一段离班考勤
                    maps.put("attendtime", new StringBuilder("离班考勤: ").append(endtime).toString());
                    maps.put("time", endtime);
                    a = 2;
                }

                if ((!StringUtils.isEmpty(time) && time.equals(s_ejecttime1)) || (type == 1 && DateUtil.getcompTime(time1, s1) > 0 && DateUtil.getcompTime(time1, s3) <= 0)) {//为第二段进班考勤
                    maps.put("attendtime", new StringBuilder("进班考勤: ").append(starttime1).toString());
                    maps.put("time", starttime1);
                    a = 3;
                }

                if ((!StringUtils.isEmpty(time) && time.equals(e_ejecttime1)) || (type == 0 && DateUtil.getcompTime(time1, s) > 0) || (type == 1 && DateUtil.getcompTime(time1, s3) > 0)) {//为第二段离班考勤
                    maps.put("attendtime", new StringBuilder("离班考勤: ").append(endtime1).toString());
                    maps.put("time", endtime1);
                    a = 4;
                }
                logger.info("Attend,queryAttendUserStatusAllStatus,status={}", a);
                Map<String, Object> list = queryAttendUserStatus(starttime, endtime, starttime1, endtime1, type, a, grouptype, groupid, shiftid, s, s1, s2, s3);
                maps.putAll(list);
            }
            logger.info("Attend,queryAttendUserStatusAll-->maps={}", maps.toString());
            if (maps != null && maps.size() > 0) {
                maps.put("datetime", new StringBuilder(gettime).append(" ").append(DateUtil.getWeeks(gettime)).toString());
                return new Result(maps);
            }
            return new Result();
        } catch (Exception e) {
            logger.info("queryAttendUserStatusAll-->erorr={}", e);
        }
        return new Result();
    }


    /**
     * @描述 private static Integer zhengchang = 1;//正常打卡
     * <p>
     * private static Integer chidao = 2;//迟到
     * <p>
     * private static Integer zaotui = 3;//早退
     * <p>
     * private static Integer weidaka = 4;//未打卡
     * <p>
     * private static Integer qingjia = 5;//请假
     * @创建人 zm
     * @创建时间 2020/2/21
     */
    public Map<String, Object> queryAttendUserStatus(String starttime, String endtime, String starttime1, String endtime1, int type, int a, Integer grouptype, Integer groupid, Integer shiftid, String s, String s1, String s2, String s3) {
        String sql = "";
        String sql1 = "";
        String gettime = DateUtil.gettime();
        int param4 = 0;//返回类型
        int param = 0;//返回类型
        String param1 = "";//考勤时间
        String param2 = "";//开始时间
        String param3 = "";//结束时间
        if (type == 0) {//一天一段考勤
            logger.info("一天一段，s={}", s);
            if (a == 1) {
                param = chidao;
                param1 = starttime;
                param2 = DateUtil.addDays(gettime, -1);
                param3 = s;
                param4 = zhengchang;
            }
            if (a == 4) {
                param = zhengchang;
                param1 = endtime1;
                param2 = s;
                param3 = DateUtil.addDays(gettime, 1);
                param4 = zaotui;
            }
        } else {//一天两段考勤
            logger.info("一天两段，s={}，s1={}，s3={}", s, s1, s3);
            if (a == 1) {
                param = chidao;
                param1 = starttime;
                param2 = DateUtil.addDays(gettime, -1);
                param3 = s2;
                param4 = zhengchang;
            }
            if (a == 2) {
                param = zhengchang;
                param1 = endtime;
                param2 = s2;
                param3 = s1;
                param4 = chidao;
            }
            if (a == 3) {
                param = chidao;
                param1 = starttime1;
                param2 = s1;
                param3 = s3;
                param4 = zhengchang;
            }
            if (a == 4) {
                param = zhengchang;
                param1 = endtime1;
                param2 = s3;
                param3 = DateUtil.addDays(gettime, 1);
                param4 = zaotui;
            }
        }
        if (grouptype == 0) {
            sql = " SELECT t.id tid,t.student_name name,t.head_portrait icon,t.class_id classid,a.attendtime time,IF((SELECT  COUNT(1) FROM  vacation WHERE student_id=t.id AND state=1 AND DATE(stime)<=DATE(NOW()) AND DATE(etime)>= DATE(NOW()))>0,5,(CASE WHEN  a.attendtime IS NULL THEN 4 WHEN a.attendtime <? THEN ? ELSE ? " +
                    "  END  )) attendtype FROM  attendance_group_user u,student t LEFT JOIN " +
                    "  attend a ON t.id=a.userid AND a.attend_group_id=? AND " +
                    "  a.state=0 AND TO_DAYS(a.attendtime)=TO_DAYS(NOW()) AND a.attendtime>=? " +
                    "  AND a.attendtime<=?  WHERE u.attend_group_id=? AND t.id=u.userid GROUP BY t.id order by a.attendtime desc";

            sql1 = "SELECT  COUNT(1) ycount,SUM(IF(attendtype = 1 OR attendtype = 2 OR attendtype = 3 , 1, 0))  scount,SUM(IF(attendtype = 4, 1, 0)) wcount FROM " +
                    "( SELECT t.id tid,t.student_name name,t.head_portrait icon,t.class_id classid,a.attendtime time,(CASE WHEN  a.attendtime IS NULL THEN 4 WHEN a.attendtime <? THEN ? ELSE ? " +
                    "  END  ) attendtype FROM  attendance_group_user u,student t LEFT JOIN " +
                    "  attend a ON t.id=a.userid AND a.attend_group_id=? AND " +
                    "  a.state=0 AND TO_DAYS(a.attendtime)=TO_DAYS(NOW()) AND a.attendtime>=? " +
                    "  AND a.attendtime<=?  WHERE u.attend_group_id=? AND t.id=u.userid GROUP BY t.id  order by a.attendtime desc ) s ";

        } else {
            sql = " SELECT t.id tid,t.name ,t.head_portrait icon,a.attendtime time,(CASE WHEN  a.attendtime IS NULL THEN 4 WHEN a.attendtime <? THEN ? ELSE ? " +
                    "  END  ) attendtype FROM  attendance_group_user u,teacher t LEFT JOIN " +
                    "  attend a ON t.id=a.userid AND a.attend_group_id=?  AND " +
                    "  a.state=0 AND TO_DAYS(a.attendtime)=TO_DAYS(NOW()) AND a.attendtime>=? " +
                    "  AND a.attendtime<=?  WHERE u.attend_group_id=? AND t.id=u.userid GROUP BY t.id order by a.attendtime desc";

            sql1 = "SELECT  COUNT(1) ycount,SUM(IF(attendtype = 1 OR attendtype = 2 OR attendtype = 3 , 1, 0))  scount,SUM(IF(attendtype = 4, 1, 0)) wcount FROM  " +
                    "(SELECT (CASE WHEN  a.attendtime IS NULL THEN  " +
                    "4 WHEN a.attendtime <? THEN ? ELSE ?   END  ) attendtype FROM  attendance_group_user u," +
                    "student t LEFT JOIN   attend a ON t.id=a.userid AND a.attend_group_id=? AND   a.state=0 " +
                    "AND TO_DAYS(a.attendtime)=TO_DAYS(NOW()) AND a.attendtime>=?   AND a.attendtime<=?" +
                    " WHERE u.attend_group_id=? AND t.id=u.userid GROUP BY t.id  order by a.attendtime desc) s                    ";
        }

        List<Map<String, Object>> mapList = null;//查询考勤组人员今天所有考勤信息
        Map<String, Object> map = null;
        try {
            mapList = attendanceJdbc.queryListMap(sql, param1, param4, param, groupid, param2, param3, groupid);
            map = attendanceJdbc.queryMap(sql1, param1, param4, param, groupid, param2, param3, groupid);
        } catch (Exception e) {
            logger.info("queryAttendUserStatus-->mapList,error={}", e);
        }
        map.put("attendlist", mapList);
        return map;
    }


    /**
     * @描述 查询对应班牌所有考勤dialog时间
     * @创建人 zm
     * @创建时间 2020/2/20
     */
    @Override
    public Map<String, Object> queryAttendGroupDialogAll(String deviceid) {
        Map<String, Object> stringObjectMap = attendanceJdbc.queryDevice(deviceid);
        if (stringObjectMap == null) {
            return null;
        }
        Object id = stringObjectMap.get("id");
        Object classid = stringObjectMap.get("classid");

        //更新班牌dialog心跳
        //service.pushClassCard(Integer.parseInt(id.toString()), "dialogflag", flag);
        String sql3 = " UPDATE bancard SET dialogflag=1 WHERE deviceid=?";
        attendanceJdbc.updateByParameter(sql3, deviceid);

        //查询这个班级班牌里面所有考勤组（目前只支持 一个班级对应一个考勤组）
        String sql = "SELECT g.id groupid,g.name groupname,g.shift_id,g.attend_group_type grouptype FROM attendance_group g,attendance_group_classid d,classes s WHERE s.id=?  AND d.attend_group_id=g.id AND d.class_id=s.id LIMIT 1";
        Map<String, Object> groupMap = null;
        try {
            groupMap = attendanceJdbc.queryMap(sql, classid);
        } catch (Exception e) {
            logger.info("queryBanAttendGroupAll,error={}", e);
        }
        if (groupMap != null) {
            //封装考情组，dialog 时间
            String shift_id = (String) groupMap.get("shift_id");
            String[] split = shift_id.split(",");
            for (int j = 0; j < split.length; j++) {
                String s = split[j];
                String weeks = getWeeks(j);
                if ("0".equals(s)) {
                    groupMap.put(weeks, null);
                } else {
                    String sql1 = " SELECT  id,name,type,starttime,endtime,starttime1,endtime1,s_ejecttime,e_ejecttime,s_ejecttime1,e_ejecttime1,school_id FROM attendance_shift WHERE  id=? and state=0";
                    Map<String, Object> map = null;
                    try {
                        map = attendanceJdbc.queryMap(sql1, s);
                    } catch (Exception e) {
                        logger.info("queryBanAttendGroupAll,error={}", e);
                    }
                    if (map != null) {
                        if ((int) map.get("type") == 0) {//一天一次考勤
                            Map<String, Object> stringObjectHashMap = new HashMap<>();
                            stringObjectHashMap.put("id", map.get("id"));//班次id
                            stringObjectHashMap.put("starttime", map.get("starttime"));
                            stringObjectHashMap.put("endtime", map.get("endtime1"));
                            stringObjectHashMap.put("s_ejecttime", map.get("s_ejecttime"));
                            stringObjectHashMap.put("e_ejecttime", map.get("e_ejecttime1"));
                            groupMap.put(weeks, stringObjectHashMap);
                        } else {
                            groupMap.put(weeks, map);
                        }
                    } else {
                        groupMap.put(weeks, null);
                    }
                }
            }
        }
        return groupMap;
    }

    @Override
    public Result findStudentFace(String deviceid) {

        //查询这个设备的班级
        String sql = "select id string from classes c where EXISTS " +
                "(select * from bancard b left join classroom  cr on(cr.id=b.classroomid) where b.deviceid=? and cr.classid=c.id) limit 1";
        //班级id
        String classId = attendanceJdbc.queryString(sql, deviceid);
        //查询班级学生人脸信息
        sql = "select sf.id,sf.url,sf.student_id,sf.class_id,s.student_name from student_faces sf " +
                "left join student s on(sf.student_id=s.id) where sf.class_id = ? and (sf.state =1 or sf.state = 3) ";

        List<Map<String, Object>> list = attendanceJdbc.queryListMap(sql, classId);
        //修改心跳
        //service.classesAndCards(classId, "faceflag", "0");
        sql = " UPDATE bancard SET faceflag=0 WHERE deviceid=?";
        attendanceJdbc.updateByParameter(sql, deviceid);
        //返回封装
        Map<String, Object> map = new HashMap<>();
        //判断如果大于100
        if (list.size() > 100) {
            //状态还有
            map.put("state", 1);
            //获取到100
            map.put("list", list.subList(0, 100));
        } else {
            //状态无
            map.put("state", 0);
            //直接返回
            map.put("list", list);
        }


        return new Result(map);
        //return new Result(list);
    }

    @Override
    public Result informStudentFace(JSONArray faceList, String deviceid) {
        logger.info("告知学生人脸注册情况");
        //要同步的人臉
        String facesId = "";

        if (faceList == null || faceList.size() == 0) {
            return new Result(CodeUtil.TELL_THE_FACE_INFORMATION_IS_EMPTY);
        }
        Map<String, Object> stringObjectMap = attendanceJdbc.queryDevice(deviceid);
        //修改学生人俩信息sql
        String sql = "UPDATE `cloud_window`.`student_faces` SET `state` = ?, push_state = 0 WHERE `id` = ? ";
        //循环人脸信息
        for (Object string : faceList) {
            Map<String, Object> map = JSON.parseObject(string.toString());
            attendanceJdbc.updateByParameter(sql, "2".equals(map.get("state").toString())?map.get("state"):1, map.get("id"));
            //如果等于成功
            if("2".equals(map.get("state").toString())){
                facesId+= map.get("id").toString()+",";
            }
        }

        try {


            //查询这个学校其他下面的班级
            sql = "select CONCAT(c.id) classid from classes c left join grade g on(g.id=c.grade_id)" +
                    " where g.school_id=? and g.other = 1";
            //查询这个学校其他下面的班级id
            List<Integer> classList = attendanceJdbc.queryListInteger(sql, new Object[]{stringObjectMap.get("school_id")});
            //循环班级id
            for (Integer classid : classList) {
                //把符合条件的数据同步到另外一张表
                sql = "INSERT INTO student_other_faces(student_faces_id,class_id,state,school_id)" +
                        "select sf.id ,? ,0, sf.school_id  from ( SELECT sf.*,sof.id sofid FROM student_faces sf " +
                        " left JOIN  student_other_faces sof on(sof.student_faces_id=sf.id and  sof.state  in(0,1,4) " +
                        "and sof.class_id =? ) where sf.state = 2 and sf.school_id =?  ) sf where sf.sofid is  null";
                attendanceJdbc.updateByParameter(sql, classid, classid, stringObjectMap.get("school_id"));

            }
            //多个班级个推，心跳
            service.classesAndCards(classList, "faceflag", "1");
            classCardService.classesAndCards(classList);


        } catch (Exception e) {
            logger.info("e", e);
        }

        try{
            haiweidaCooperativeSchoolJdbc.haiweidaStudentFaces(facesId.substring(0, facesId.length() - 1),stringObjectMap.get("school_id").toString());
        }catch (Exception e){
            logger.info("e", e);
        }

        return new Result();
    }

    @Override
    public Result findDeleteStudentFace(String deviceid) {
        //查询这个设备的班级
        String sql = "select id string from classes c where EXISTS " +
                "(select * from bancard b left join classroom  cr on(cr.id=b.classroomid) where b.deviceid=? and cr.classid=c.id) limit 1";
        //班级id
        String classId = attendanceJdbc.queryString(sql, deviceid);
        //查询班级学生人脸信息
        sql = "select sf.id,sf.url,sf.student_id,sf.class_id,s.student_name from student_faces sf " +
                "left join student s on(sf.student_id=s.id) where sf.class_id = ? and sf.state =5 and sf.push_state=1";

        List<Map<String, Object>> list = attendanceJdbc.queryListMap(sql, classId);
        //修改心跳
        service.classesAndCards(classId, "delfaceflag", "0");
        return new Result(list);
    }

    /**
     * @描述 根据学生id 查学生最新一天请假记录
     * @创建人 zm
     * @创建时间 2020/3/27
     */
    @Override
    public Map<String, Object> queryVacationById(Integer id) {
        String sql = "SELECT v.id,v.student_id,s.student_name ,s.head_portrait ,v.type,DATE_FORMAT(v.stime,'%Y-%m-%d %H:%i') stime,DATE_FORMAT(v.etime,'%Y-%m-%d %H:%i') etime,(CASE   WHEN v.state=2 THEN 1  WHEN v.state=5 THEN 1  " +
                "WHEN v.state=4 THEN 1 WHEN v.state=3 THEN 2  WHEN v.state=6 THEN 2  ELSE 0 END ) state," +
                "DATE_FORMAT(v.opertime ,'%Y-%m-%d') opertime ,c.name classname,c.id cid ,t.id tid,t.name tname FROM vacation v,student s,classes c LEFT JOIN  teacher t ON c.class_teacher_id=t.id  WHERE s.id=v.student_id AND c.id=s.class_id AND v.student_id=? ORDER BY v.opertime DESC LIMIT 1";
        Map<String, Object> map = new HashMap<>();
        try {
            map = attendanceJdbc.queryMap(sql, id);
        } catch (Exception e) {
            logger.info("queryStudentVacationById(==>,error={}", e);
        }
        return map;
    }


    /**
     * @描述 (广西)校牌，请假放行
     * @创建人 zm
     * @创建时间 2020/4/4
     */
    @Override
    public Result release(Integer id) {
        try {
            String accessToken = wXJdbc.getAccessToken(1);
            String sql = "INSERT INTO import_and_export_schools(student_id,type,time) VALUES(?,1,NOW())";
            String sql2 = "INSERT INTO all_notice(jurisdiction_id,type,student_id,content,class_id,school_id,tapplet,opertime) VALUES(1,4,?,?,?,?,1,now())";
            attendanceJdbc.updateByParameter(sql, id);
            sql = "SELECT t.student_name tname,s.school_name sname,c.id,c.school_id FROM student t LEFT JOIN  classes c ON t.class_id=c.id LEFT JOIN  school s ON  c.school_id=s.id WHERE  t.id=?";
            Map<String, Object> map = attendanceJdbc.queryMap(sql, id);
            attendanceJdbc.updateByParameter(sql2, id, DateUtil.getTimeAndMinutes() + "已离校", map.get("id"), map.get("school_id"));
            Map<String, Object> pushMap = new HashMap<>();
            pushMap.put("name2", map.get("tname"));
            pushMap.put("phrase3", "请假离校");
            pushMap.put("date4", DateUtil.getTimeAndMinutes());
            pushMap.put("thing5", map.get("sname"));
            pushMap.put("thing9", map.get("tname") + "同学离开学校");
            //解析后的数据
            JSONObject json = TemplateTools.initializationData(pushMap);
            //查询家长的小程序openId
            sql = "select p.open_id_one string from parent p  LEFT JOIN parent_student ps on(ps.parent_id=p.id) where ps.student_id=?";
            //家长openid
            String openId = attendanceJdbc.queryString(sql, id);
            //推送订阅消息
            WXUtil.sendWechatmsgToUser(accessToken, openId, "SgHgOWeECoiWY6tukJP1RDq1edrJT2bP-Z4UdIe0-c4", "", json, "", "");
            attendanceJdbc.updateSubscribe(openId, "SgHgOWeECoiWY6tukJP1RDq1edrJT2bP-Z4UdIe0-c4");
            return new Result();
        } catch (Exception e) {
            logger.info("release==>error={}", e);
        }
        return new Result(CodeUtil.NO_DOCKING_INFORMATION);
    }

    /**
     * @描述 家长留言/学生
     * @创建人 zm
     * @创建时间 2020/3/27
     */
    @Override
    public Map<String, Object> queryParentsLeaveMessages(Integer id, Integer type) {//学生id
        Map<String, Object> map = new HashMap<>();
        String sql = "SELECT  t.id tid,t.student_name tname,p.id pid,p.name pname  FROM student t LEFT JOIN parent_student s  ON s.student_id=t.id LEFT JOIN parent p ON  s.parent_id=p.id WHERE t.id=?  limit 1";
        String sql1 = "SELECT  c.id,c.type,c.state,c.content,DATE_FORMAT(c.opertime,'%Y-%m-%d %H:%i') opertime FROM parent_chat c,student t  WHERE c.student_id=t.id AND t.id=? ORDER BY c.id desc limit 0,50";
        try {
            map = attendanceJdbc.queryMap(sql, id);
            List<Map<String, Object>> maps = attendanceJdbc.queryListMap(sql1, id);
            //让list集合倒序
            Collections.reverse(maps);
            map.put("list", maps);
        } catch (Exception e) {
            logger.info("queryStudentVacationById==>,error={}", e);
        }
        sql = "update parent_chat set state=1  where student_id=? and type=1";
        if (type == 1) {
            attendanceJdbc.updateByParameter(sql, id);
        } else {
            sql = "update parent_chat set state=1  where student_id=? and type=0";
            attendanceJdbc.updateByParameter(sql, id);
        }
        return map;
    }

    /**
     * @描述 添加留言
     * @创建人 zm
     * @创建时间 2020/3/27
     */
    @Override
    public long addParentsLeaveMessages(Integer id, Integer type, String content) {//学生id
        String sql = "insert into `parent_chat` (`student_id`, `type`, `content`, `opertime`) values(?,?,?,now())";
        int i = attendanceJdbc.updateByParameter(sql, id, type, content);
        if (type == 1) {
            sql = "SELECT  class_id  string FROM student WHERE id=?";
            String s = attendanceJdbc.queryString(sql, id);
            service.classesAndCards(s, "noticeflag", "1");
            classCardService.classesAndCards(s);
        } else {
            officialAccountPush(id, content);
        }
        return i;
    }

    /**
     * 公众号推送
     *
     * @param id
     */
    public void officialAccountPush(Integer id, String content) {

        //获取token
        try {
            String accessToken = wXJdbc.getOfficialAccountAccessToken(0);

            //查询家长的小程序openId
            String sql = "select p.open_id_one,p.id,p.open_id_two,p.name  from parent p  LEFT JOIN parent_student ps on(ps.parent_id=p.id) where ps.student_id=?";
            String sql1 = " SELECT student_name string FROM student WHERE id=?";

            //家长的openId
            String openId = null;
            String name = null;

            //家长openid
            Map<String, Object> parent = attendanceJdbc.queryMap(sql, id);
            String s = attendanceJdbc.queryString(sql1, id);
            openId = (String) parent.get("open_id_two");
            name = (String) parent.get("name");


            //判断openId是否为空
            if (!StringUtils.isEmpty(openId)) {
                Map<String, Object> pushMap = new HashMap<>();

                pushMap.put("first", "家长您好，" + s + "同学给您发送了一条新的留言");
                pushMap.put("keyword1", name);
                pushMap.put("keyword2", DateUtil.time());
                pushMap.put("keyword3", new String(new Base64().decode(content), "UTF-8"));
                pushMap.put("remark", "感谢您的支持。");

                //跳转小程序信息
                JSONObject appletJson = new JSONObject();
                appletJson.put("appid", "wx30b606bac7775eba");
                appletJson.put("pagepath", "pages/messages/index");

                //解析后的数据
                JSONObject json = TemplateTools.initializationData(pushMap);
                //推送公众号信息
                WXUtil.officialAccountPush(accessToken, openId, "kqA-il5-6F-I1C6_Aw90bfeStmM-gF9RUxVrWOuLJWA", "", appletJson, json);
            }
        } catch (UnsupportedEncodingException e) {

        }
    }


    /**
     * @描述 修改留言状态
     * @创建人 zm
     * @创建时间 2020/3/27
     */
    @Override
    public long updateParentsLeaveMessagesState(Integer id) {//留言id
        String sql = "UPDATE  parent_chat SET state=1 WHERE id=?";
        return attendanceJdbc.updateByParameter(sql, id);
    }

    @Override
    public Result findSchoolFace(String deviceid) {

        Map<String, Object> stringObjectMap = attendanceJdbc.queryDevice(deviceid);

        //查询整个学校的学生人脸
        String sql = "SELECT sof.id,  sf.url, sf.student_id,  sf.class_id, s.student_name " +
                " FROM student_other_faces sof  LEFT JOIN student_faces sf ON ( sof.student_faces_id = sf.id ) " +
                " LEFT JOIN student s ON ( sf.student_id = s.id ) " +
                " WHERE sof.class_id = ?  AND sof.state =0 and s.student_name is not null";

        List<Map<String, Object>> list = attendanceJdbc.queryListMap(sql, stringObjectMap.get("classid"));
        //修改心跳
        service.classesAndCards(stringObjectMap.get("classid").toString(), "faceflag", "0");
        //返回封装
        Map<String, Object> map = new HashMap<>();
        //判断如果大于100
        if (list.size() > 100) {
            //状态还有
            map.put("state", 1);
            //获取到100
            map.put("list", list.subList(0, 100));
        } else {
            //状态无
            map.put("state", 0);
            //直接返回
            map.put("list", list);
        }


        return new Result(map);
        //return new Result(list);
    }

    @Override
    public Result informSchoolFace(JSONArray faceList, String deviceid) {
        if (faceList == null || faceList.size() == 0) {
            return new Result(CodeUtil.TELL_THE_FACE_INFORMATION_IS_EMPTY);
        }

        //修改学生人俩信息sql
        String sql = "UPDATE `student_other_faces` SET `state` = ? WHERE `id` = ? ";
        //循环人脸信息
        for (Object string : faceList) {
            Map<String, Object> map = JSON.parseObject(string.toString());
            attendanceJdbc.updateByParameter(sql, map.get("state"), map.get("id"));
        }

        return new Result();
    }

    @Override
    public Result findDeleteStudentOtherFace(String deviceid) {
        Map<String, Object> stringObjectMap = attendanceJdbc.queryDevice(deviceid);

        //查询整个学校的学生人脸
        String sql = "SELECT sof.id,  sf.url, sf.student_id,  sf.class_id, s.student_name " +
                " FROM student_other_faces sof  LEFT JOIN student_faces sf ON ( sof.student_faces_id = sf.id ) " +
                " LEFT JOIN student s ON ( sf.student_id = s.id ) " +
                " WHERE sof.class_id = ?  AND sof.state =4 and s.student_name is not null";

        List<Map<String, Object>> list = attendanceJdbc.queryListMap(sql, stringObjectMap.get("classid"));

        return new Result(list);
    }


    /**
     * 把学生的考勤推送家长 小程序
     *
     * @param studentId  学生id
     * @param attendtype 考勤类型 2 进班正常 3 进班迟到  6 离班早退 9 离班正常
     * @return
     */
    public int attendPush(Integer studentId, Integer attendtype) {
        //查询家长的小程序openId
        String sql = "select p.open_id_one,p.id,p.open_id_two  from parent p  LEFT JOIN parent_student ps on(ps.parent_id=p.id)where ps.student_id=?";
        //家长openid
        Map<String, Object> parent = attendanceJdbc.queryMap(sql, studentId);
        //家长的openId
        String openId = (String) parent.get("open_id_one");

        sql = "select COUNT(1) count from user_subscription_template ust left JOIN we_chat_template wt " +
                "on(wt.id=ust.template_id) where wt.template_id='EbVc_-bWlSb_nYveQzlK37WjIAhWBkvh_8nHF3x1LIA' and ust.open_id =? and ust.state=0 ";
        //判断这个用户这个小程序是否订阅了
        int count = attendanceJdbc.queryCount(sql, openId);
        //判断openId是否为空
        if (!StringUtils.isEmpty(openId) && count > 0) {

            String accessToken = wXJdbc.getAccessToken(1);
            //查询学生名字
            sql = "select student_name string from student where id = ?";
            String studenName = attendanceJdbc.queryString(sql, studentId);
            Map<String, Object> pushMap = new HashMap<>();
            pushMap.put("thing6", studenName);
            pushMap.put("phrase7", getAttendtype(attendtype));
            pushMap.put("time8", DateUtil.time());

            //解析后的数据
            JSONObject json = TemplateTools.initializationData(pushMap);
            //推送订阅消息
            WXUtil.sendWechatmsgToUser(accessToken, openId, "EbVc_-bWlSb_nYveQzlK37WjIAhWBkvh_8nHF3x1LIA", "", json, "", "");
            wXJdbc.updateSubscribe(openId, "EbVc_-bWlSb_nYveQzlK37WjIAhWBkvh_8nHF3x1LIA");
        }
        return 1;
    }

    /**
     * 获取类型
     *
     * @param attendtype 2 正常 3 进班迟到  6 离班早退 9 离班正常
     * @return
     */
    public String getAttendtype(Integer attendtype) {
        if (attendtype == 2) {
            return "进班正常";
        } else if (attendtype == 3) {
            return "进班迟到";
        } else if (attendtype == 6) {
            return "离班早退";
        } else if (attendtype == 9) {
            return "离班正常";
        } else {
            return "正常";
        }
    }


    public String getWeeks(int s) {
        String week = "";
        if (s == 0) {
            week = "monday";
        } else if (s == 1) {
            week = "tuesday";
        } else if (s == 2) {
            week = "wednesday";
        } else if (s == 3) {
            week = "thursday";
        } else if (s == 4) {
            week = "friday";
        } else if (s == 5) {
            week = "saturday";
        } else if (s == 6) {
            week = "sunday";
        }
        return week;
    }


    /**
     * @描述 根据班牌id查活动信息
     * @创建人 zm
     * @创建时间 2020/5/12
     */
    @Override
    public Result queryParentActivitiyByDeviceid(String deviceid) {
        Map<String, Object> stringObjectMap = attendanceJdbc.queryDevice(deviceid);//判断设备是否存在 并获取设备相关信息
        if (stringObjectMap == null) {
            return new Result(CodeUtil.DEVICE_AFTER_OPERATION);
        }
        Object classid = stringObjectMap.get("classid");//班级id
        String sql = "SELECT p.id,p.name,s.class_icon,s.id classid,DATE_FORMAT(NOW(),'%Y-%m-%d %H:%i:%s') gtime,DATE_FORMAT((NOW()+INTERVAL 1 MINUTE),'%Y-%m-%d %H:%i:%s') rtime,DATE_FORMAT(stime,'%Y-%m-%d %H:%i:%s') stime,DATE_FORMAT(etime,'%Y-%m-%d %H:%i:%s') etime FROM parent_activities p,classes  s   WHERE p.class_id=s.id AND p.school_id=s.school_id AND s.id=? AND p.start=1 AND etime>NOW() ORDER BY p.opertime DESC LIMIT 1";
        Map<String, Object> map = null;
        try {
            map = attendanceJdbc.queryMap(sql, classid);
        } catch (Exception e) {

        }
        return new Result(map);
    }


    /**
     * @描述 根据学生卡号查询学生id
     * @创建人 zm
     * @创建时间 2020/6/30
     */
    @Override
    public Result queryStudentIdByCardNumber(String deviceid, String cardNumber) {
        Map<String, Object> stringObjectMap = attendanceJdbc.queryDevice(deviceid);//判断设备是否存在 并获取设备相关信息
        if (stringObjectMap == null) {
            return new Result(CodeUtil.DEVICE_AFTER_OPERATION);
        }
        //卡号长度9前面补0
        if(cardNumber.length()==9){
            cardNumber="0"+cardNumber;
        }
        Object school_id = stringObjectMap.get("school_id");//学校id
        String sql = "SELECT id,student_name name FROM  student WHERE school_id=? AND card_number=? LIMIT 1";
        Map<String, Object> map = null;
        try {
            map = attendanceJdbc.queryMap(sql, school_id, cardNumber);
        } catch (Exception e) {

        }
        if (map == null || map.size() <= 0) {
            return new Result(CodeUtil.CARDNUMBERDOES_NOTEXIST);
        }
        return new Result(map);
    }


    /**
     * @描述 查询活动信息签到详情
     * @创建人 zm
     * @创建时间 2020/5/12
     */
    @Override
    public Result queryActivitiyByIdList(Integer id, String deviceid) {//活动id
        String sql = "SELECT COUNT(1) ints FROM student t,parent_activities p WHERE t.class_id=p.class_id AND p.id=?";
        Integer integer = attendanceJdbc.queryInteger(sql, id);
        sql = " SELECT t.id,t.student_name ,t.head_portrait FROM    parent_activities p,parent_activities_log g,student t  WHERE p.id=g.parent_activities_id AND p.class_id=t.class_id  AND t.id=g.student_id AND p.id=? GROUP BY t.id ORDER BY g.opertime DESC";
        List<Map<String, Object>> ylist = attendanceJdbc.queryListMap(sql, id);
        sql = "  SELECT t.id,t.student_name ,t.head_portrait,g.id FROM    (parent_activities p,student t) LEFT JOIN  parent_activities_log g ON ( t.id=g.student_id AND p.id=g.parent_activities_id) " +
                "  WHERE  p.class_id=t.class_id  AND p.id=? AND g.id IS NULL GROUP BY t.id ORDER BY g.opertime DESC ";
        List<Map<String, Object>> wlist = attendanceJdbc.queryListMap(sql, id);
        Map<String, Object> map = new HashMap<>();
        map.put("zcount", integer);//总人数
        map.put("ycount", ylist.size());//已到人数
        map.put("wcount", wlist.size());//未到人数
        map.put("ylist", ylist);//已到人数信息
        map.put("wlist", wlist);//未人数信息
        //service.deviceidAndCards(deviceid, "refreshflag", "0");
        String sql2 = " UPDATE bancard SET refreshflag=0 WHERE deviceid=?";
        attendanceJdbc.updateByParameter(sql2, deviceid);
        return new Result(map);
    }

    /**
     * 把学生的考勤推送家长 公众号
     *
     * @param studentId  学生id
     * @param attendtype 考勤类型 2 进班正常 3 进班迟到  6 离班早退 9 离班正常
     */
    public void officialAccountPush(Integer studentId, Integer attendtype) {

        String accessToken = wXJdbc.getOfficialAccountAccessToken(0);
        //查询家长的小程序openId
        String sql = "select p.open_id_one,p.id,p.open_id_two  from parent p  LEFT JOIN parent_student ps on(ps.parent_id=p.id)where ps.student_id=?";
        //家长openid
        Map<String, Object> parent = attendanceJdbc.queryMap(sql, studentId);
        //家长的openId
        String openId = (String) parent.get("open_id_two");

        //判断openId是否为空
        if (!StringUtils.isEmpty(openId)) {


            //查询学生名字
            sql = "select student_name string from student where id = ?";
            String studenName = attendanceJdbc.queryString(sql, studentId);
            Map<String, Object> pushMap = new HashMap<>();
            pushMap.put("first", "家长您好，您的孩子有一条新的考勤信息。");
            pushMap.put("keyword1", studenName);
            pushMap.put("keyword2", DateUtil.time());
            pushMap.put("keyword3", getAttendtype(attendtype));
            pushMap.put("remark", "感谢您的支持。");

            //跳转小程序信息
            JSONObject appletJson = new JSONObject();
            appletJson.put("appid", "wx30b606bac7775eba");
            appletJson.put("pagepath", "pages/attendance/index");

            //解析后的数据
            JSONObject json = TemplateTools.initializationData(pushMap);
            //推送公众号信息
            WXUtil.officialAccountPush(accessToken, openId, "31YxmArTVzKpLSYIJ5EmH2PR35mMNfu96_VLOlTebBE", "", appletJson, json);

        }
    }
}
